module(..., package.seeall)

require "utils.table"
require "moaix.input.common"


----------------------------------------------------------------------------------------------------
-- Setup module signals, channel, and callback binding shortcut functions
----------------------------------------------------------------------------------------------------
SIGNALS = {KEY_PRESS    = "key press", 
           KEY_RELEASE  = "key release"}
channel, bind_shortcuts = moaix.input.common.make_channel("keyboard", SIGNALS)
table.copy(bind_shortcuts, _M)  -- make bind shortcuts available at module level

----------------------------------------------------------------------------------------------------
-- Module state variables and input handler
----------------------------------------------------------------------------------------------------
pressed_keys = {}

local function keyboard_handler(key, pressed)
    --[[ Called when a key is pressed or released. ]]
    pressed_keys[key] = pressed or nil
    -- print(("%s key %d - %s"):format(pressed and "Pressed" or "Released", key, string.char(key)))
    -- print(("Currently pressed keys: %s"):format(table.repr(pressed_keys)))
    channel:emit(pressed and SIGNALS.KEY_PRESS or SIGNALS.KEY_RELEASE, {key=key})
end

----------------------------------------------------------------------------------------------------
-- Link input handler to MOAI's keyboard device
----------------------------------------------------------------------------------------------------
function init()
    if MOAIInputMgr.device.keyboard == nil then
        print("WARNING: Keyboard unavailable.")
        return false
    else
        print("INFO: Setting up keyboard input handler...")
        MOAIInputMgr.device.keyboard:setCallback(keyboard_handler)
        return true
    end
end
